package com.ptswitch.material.service.impl;

import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hxzon.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ptswitch.material.dao.ContractItemMapper;
import com.ptswitch.material.model.contract.ContractItem;
import com.ptswitch.material.service.ContractItemService;

@Service
public class ContractItemServiceImpl implements ContractItemService {

    private static final Logger logger = LoggerFactory.getLogger(ContractItemServiceImpl.class);
    @Autowired
    private ContractItemMapper contractItemMapper;

    @Override
    public List<ContractItem> findAll(long first, long size) {
        return contractItemMapper.findAll(first, size);
    }

    @Override
    public List<ContractItem> findByExamine(long id, boolean pass) {
        if (pass) {
            return contractItemMapper.findByExamine(id, pass);
        } else {
            return contractItemMapper.findByExamine(id, pass);
        }
    }

    @Override
    public List<ContractItem> findByReceiving(long id, boolean receiving) {
        if (receiving) {
            return contractItemMapper.findByReceiving(id, receiving);
        } else {
            return contractItemMapper.findByReceiving(id, receiving);
        }
    }

    @Override
    public List<ContractItem> findByReturn(long id) {
        return contractItemMapper.findByReturn(id);
    }

    @Override
    public List<ContractItem> findByContract(long id) {
        return contractItemMapper.findByContract(id);
    }

    @Override
    public boolean existContractItemCode(ContractItem item) {
        return contractItemMapper.existContractItemCode(item);
    }

    private Pattern p = Pattern.compile(".*-\\d*-(\\d*)");

    @Override
    public String emptyCode(String code) {
        code = StringUtil.escapeSql(code);
        String lastCode = contractItemMapper.emptyCode(code);
        logger.debug("get empty code:{}", lastCode);
        Matcher m = p.matcher(lastCode);
        try {
            m.matches();
            int index = Integer.parseInt(m.group(1)) + 1;
            return code + "-" + index;
        } catch (RuntimeException e) {
            logger.error("get empty code fail", e);
        }
        return code;
    }

    @Override
    public void save(ContractItem item) {
    }

    @Override
    public void saveAll(Collection<ContractItem> items) {
    }

    @Override
    public ContractItem findById(long id) {
        return null;
    }

    @Override
    public void delete(ContractItem item) {
    }

}
